import { IndexWrapper } from "./style";
import { Grid, Card, Link, Comment, List } from "@arco-design/web-react";
import avatarImg from "../../assets/img/BiazfanxmamNRoxxVxka.png";
import reactImg from "../../assets/img/kZzEzemZyKLKFsojXItE.png";
import vueImg from "../../assets/img/vue.ico";
import antDesignImg from "../../assets/img/dURIMkkrRFpPgTuzkwnB.png";
import githubImg from "../../assets/img/ODF.svg";
import * as echarts from "echarts";
import { useEffect, useRef, useState } from "react";
import { useAppDispatch, useAppSelector } from "../../store";
import {
  fetchGetIndexChartAction,
  fetchLeaveWordListAction,
} from "../../store/modules/leaveWord";
import { useAutoScrollList } from "../../hooks/useAutoScrollList";

const Row = Grid.Row;
const Col = Grid.Col;

const IndexPage = () => {
  const dispatch = useAppDispatch();
  const { chartData, leaveWordList } = useAppSelector(
    (state) => state.leaveWord
  );

  useEffect(() => {
    dispatch(fetchGetIndexChartAction());
    dispatch(
      fetchLeaveWordListAction({
        pageNum: 1,
        pageSize: 7,
      })
    );
  }, [dispatch]);
  /**
   * @只获取留言列表内容
   */
  const getLeaveWordListContent = () => {
    return leaveWordList?.map(({ id, content }) => ({ id, content }));
  };
  //*留言评论数据
  const leaveWordContent = getLeaveWordListContent();
  // console.log(leaveWordContent);

  const {
    wrapperStyle,
    innerStyle,
    itemHeight,
    loopList,
    onMouseEnter,
    onMouseLeave,
  } = useAutoScrollList(leaveWordContent, 4, 85, 2000);

  /**
   * @echart的数据
   */
  const userIllnessCount = chartData?.userIllnessCount || [];
  const getChartDataName = () => {
    return Array.isArray(userIllnessCount)
      ? userIllnessCount.map((item) => item?.illnessName || "")
      : [];
  };
  const getChartDataCount = () => {
    return Array.isArray(userIllnessCount)
      ? userIllnessCount.map((item) => item?.illnessCount || 0)
      : [];
  };
  useEffect(() => {
    type EChartsOption = echarts.EChartsOption;
    const chartDom = document.getElementById("firstMain")!;
    const myChart = echarts.init(chartDom);
    // let option: EChartsOption;
    const option: EChartsOption = {
      tooltip: {
        trigger: "item",
      },
      legend: {
        top: "2%",
        width: "100%",
        height: "20px",
      },
      series: [
        {
          name: "文章点赞情况",
          type: "pie",
          center: ["50%", "55%"],

          radius: ["40%", "70%"],
          avoidLabelOverlap: false,
          padAngle: 5,
          itemStyle: {
            borderRadius: 10,
          },
          label: {
            // show: false,
            position: "center",
          },
          emphasis: {
            label: {
              show: true,
              fontSize: 50,
              fontWeight: "bold",
            },
          },
          labelLine: {
            show: false,
          },
          data: [
            { value: 1048, name: "泌尿系统疾病" },
            { value: 735, name: "肾结石的形成与治疗" },
            { value: 580, name: "尿路感染" },
            { value: 484, name: "儿童泌尿健康" },
            { value: 300, name: "尿液健康" },
          ],
        },
      ],
    };

    myChart.setOption(option);
    window.addEventListener("resize", () => myChart.resize());
  }, [chartData]);
  useEffect(() => {
    // if (!chartData) return;
    const chartDateCount = getChartDataCount();
    const chartDateName = getChartDataName();

    const chartDom = document.getElementById("secondMain")!;
    const myChart = echarts.init(chartDom);

    const option: echarts.EChartsOption = {
      title: {
        text: "用户标签分类", // 图表主标题
        left: "center", // 水平居中
        top: 10, // 贴顶部显示
        textStyle: {
          fontSize: 14, // 标题字体大小
        },
      },
      tooltip: {
        trigger: "axis",
        axisPointer: {
          type: "shadow",
        },
      },
      // 2. 移除legend（如果不需要图例）
      grid: {
        left: "3%",
        top: "15%", // 顶部留出更多空间给标题
        right: "3%",
        bottom: "10%",
        containLabel: true,
      },
      xAxis: {
        type: "value",
        // 3. 缩小坐标轴字体
        axisLabel: {
          fontSize: 10,
        },
      },
      yAxis: {
        type: "category",
        data: chartDateName,
        // 4. 缩小y轴字体
        axisLabel: {
          fontSize: 10,
        },
      },
      series: [
        {
          name: "用户标签分类", // 保留系列名（会在tooltip中显示）
          type: "bar",
          stack: "total",
          // 5. 缩小柱状图宽度
          barWidth: "60%",
          label: {
            show: true,
            position: "right",
            fontSize: 10, // 缩小标签字体
          },
          emphasis: {
            focus: "series",
          },
          data: chartDateCount,
        },
      ],
    };

    window.addEventListener("resize", () => myChart.resize());
    myChart.setOption(option);
  }, [chartData]);
  const echartData = [
    {
      key: 1,
      name: "React",
      src: reactImg,
      title:
        "熟悉使用React,熟悉常见Reacthooks,封装自定义hooks，愿意去深度学习react底层原理",
      time: "2005年3月至6月",
      link: "https://zh-hans.react.dev/learn",
    },
    {
      key: 2,
      name: "Vue",
      src: vueImg,
      title: "熟悉使用Vue，愿意去深度学习Vue底层原理",
      time: "2005年7月至8月",
      link: "https://cn.vuejs.org/",
    },
    {
      key: 3,
      name: "Node",
      src: reactImg,
      title: "熟悉Node,了解koa，express等框架，并使用",
      time: "2005年7月至8月",
      link: "https://nodejs.cn/download/",
    },
    {
      key: 4,
      name: "Ant Design",
      src: antDesignImg,
      title: "熟悉使用antDesign,arcoDesign,Vant等组件库",
      time: "2005年3月至8月",
      link: "https://ant-design.antgroup.com/index-cn?locale=zh-CN",
    },
    {
      key: 5,
      name: "github地址",
      src: githubImg,
      title: "经常使用github了解开源项目",
      time: "2005年3月至6月",
      link: "https://github.com/skyer-div/coderesin_react",
    },
    {
      key: 6,
      name: "React Native",
      src: reactImg,
      title: "了解React Native",
      time: "2005年8月至9月",
    },
  ];
  /**
   *@列表滚动
   */
  // const [currentIndex, setCurrentIndex] = useState(0);
  // const scrollRef = useRef<HTMLDivElement>(null);
  // const visibleCount = 4; // 一次显示4条
  // const scrollInterval = 2000; // 3秒滚动一次
  // useEffect(() => {
  //   if (!leaveWordContent || leaveWordContent.length === 0) return;
  //   const timer = setInterval(() => {
  //     setCurrentIndex((prev) => {
  //       // 如果到达最后一条，回到第一条
  //       if (prev >= leaveWordContent.length - 1) return 0;
  //       return prev + 1;
  //     });
  //   }, scrollInterval);
  //   return () => clearInterval(timer);
  // }, [leaveWordContent]);
  // 获取当前要显示的4条数据
  // const getVisibleItems = () => {
  //   if (!leaveWordContent || leaveWordContent.length === 0) return [];
  //   const items = [];
  //   // 从currentIndex开始取4条数据
  //   for (let i = 0; i < visibleCount; i++) {
  //     const index = (currentIndex + i) % leaveWordContent.length;
  //     items.push(leaveWordContent[index]);
  //   }
  //   return items;
  // };

  return (
    <IndexWrapper>
      <div className="headerWrapper">
        <Row style={{ marginBottom: 16 }}>
          <Col span={18}>
            <div className="headerLeft">
              <div className="avatarImg">
                <img src={avatarImg} alt="头像" />
              </div>
              <div className="headerLeftContent">
                <div className="headerLeftItem">
                  <h3>你好呀，小哥哥小姐姐，欢迎进入我的网页!</h3>
                </div>
                <div className="headerLeftItem">
                  <p>赣南医科大学-24物联网工程一班-前端菜鸟-曾维杰</p>
                </div>
              </div>
            </div>
          </Col>
          <Col span={6}>
            <div className="headerRight">
              <div className="showData">
                <div className="dataItem">
                  <span className="label">技术栈</span>
                  <span className="data">6</span>
                </div>
              </div>
              <div className="showData">
                <div className="dataItem">
                  <span className="label">校内排名</span>
                  <span className="data">48/105</span>
                </div>
              </div>
              <div className="showData">
                <div className="dataItem">
                  <span className="label">访客</span>
                  <span className="data">1024</span>
                </div>
              </div>
            </div>
          </Col>
        </Row>
      </div>
      <div className="contentWrapper">
        <Row style={{ alignItems: "flex-start" }}>
          <Col span={17}>
            <div className="contentLeftWrapper">
              <Card
                style={{ width: "100%" }}
                title="技术栈"
                extra={<Link style={{ userSelect: "none" }}>所有专业技能</Link>}
              >
                <div className="contentLeftBody">
                  {echartData.map((item) => {
                    return (
                      <div className="contentLeftBodyItem" key={item.key}>
                        <div className="card-meta">
                          <img src={item.src}></img>
                          <span>
                            <a target="_blank" href={item.link}>
                              {item.name}
                            </a>
                          </span>
                        </div>
                        <p>{item.title}</p>
                        <p>学习时间：{item.time}</p>
                      </div>
                    );
                  })}
                </div>
              </Card>
            </div>

            <div
              className="commentWrapper"
              style={wrapperStyle}
              onMouseEnter={onMouseEnter}
              onMouseLeave={onMouseLeave}
            >
              <div className="commentList" style={innerStyle}>
                <List>
                  {/* <List.Item style={{ backgroundColor: "var(--color-bg-2)" }}>
                    留言
                  </List.Item> */}
                  {loopList?.map((item, index) => (
                    <List.Item
                      key={index}
                      style={{
                        backgroundColor: "var(--color-bg-2)",
                        height: itemHeight,
                      }}
                    >
                      <Comment
                        author={"骗你来学前端"}
                        avatar={avatarImg}
                        content={item.content}
                      />
                    </List.Item>
                  ))}
                </List>
              </div>
            </div>
            {/* <div className="commentWrapper" ref={scrollRef}>
              <List>
                <List.Item style={{ backgroundColor: "var(--color-bg-2)" }}>
                  留言
                </List.Item>
                {getVisibleItems().map((item) => {
                  return (
                    <List.Item
                      key={item.id}
                      style={{ backgroundColor: "var(--color-bg-2)" }}
                    >
                      <Comment
                        author={"我是个托"}
                        avatar={avatarImg}
                        content={item.content}
                        actions={[]}
                      ></Comment>
                    </List.Item>
                  );
                })}
              </List>
            </div> */}
          </Col>
          <Col span={7}>
            <div className="contentRightWrapper">
              <Card className="firstMain">
                <div
                  id="firstMain"
                  style={{
                    width: "100%",
                    height: "100%",
                  }}
                ></div>
              </Card>
              <Card className="secondMain">
                <div
                  id="secondMain"
                  style={{ width: "100%", height: "100%" }}
                ></div>
              </Card>
            </div>
          </Col>
        </Row>
      </div>
    </IndexWrapper>
  );
};
export default IndexPage;
